// record.js
const app = getApp()
Page({
  data: {
    amount: '',
    date: '',
    category: '',
    note: ''
  },
  onLoad: function () {
    // 页面加载时，设置默认日期为今天
    this.setData({
      date: this.formatDate(new Date())
    })
  },
  formatDate: function (date) {
    // 格式化日期为 YYYY-MM-DD
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },
  bindAmountInput: function (e) {
    this.setData({
      amount: e.detail.value
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindCategoryInput: function (e) {
    this.setData({
      category: e.detail.value
    })
  },
  bindNoteInput: function (e) {
    this.setData({
      note: e.detail.value
    })
  },
  submitRecord: function () {
    // 提交记账信息
    const { amount, date, category, note } = this.data
    if (!amount) {
      wx.showToast({
        title: '请输入金额',
        icon: 'none'
      })
      return
    }
    const newRecord = { amount, date, category, note }
    app.globalData.records.push(newRecord)
    app.globalData.totalExpense += parseFloat(amount)
    wx.showToast({
      title: '记账成功',
      icon: 'success',
      duration: 2000
    })
    // 延迟返回首页，让用户看到成功提示
    setTimeout(() => {
      wx.navigateBack()
    }, 2000)
  }
})
